#!/usr/bin/env python
# -*- coding:utf-8 -*-

import urllib
import urllib2
from lxml import etree
import lxml.html


def loadPage(url):
    """
        作用：根据url发送请求，获取服务器响应文件
        url: 需要爬取的url地址
        filename : 处理的文件名
    """

    # 如果加上headers可能会不能解析，具体原因不清楚
    # headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"}
    request = urllib2.Request(url)
    html = urllib2.urlopen(request).read()

    content = etree.HTML(html)
    # 或者
    # content = lxml.html.document_fromstring(html)
    # print(etree.tostring(content))

    link_list = content.xpath('//div[@class="threadlist_lz clearfix"]/div/a[@class="j_th_tit "]/@href')
    print(len(link_list))
    for link in link_list:
        loadImage('http://tieba.baidu.com' + link)


def loadImage(fulllink):
    """
     取出每个帖子的每个图片的链接
    """
    # 如果加header可能不能解析
    # headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    request = urllib2.Request(fulllink)
    html = urllib2.urlopen(request).read()
    content = etree.HTML(html)
    # content = lxml.html.document_fromstring(html)
    # print(etree.tostring(content))
    link_list = content.xpath('//img[@class="BDE_Image"]/@src')
    print(link_list)
    for link in link_list:
        writeImage(link)


def writeImage(link):
    """
        作用：将html内容写入到本地
        html：服务器相应文件内容
    """
    # 文件写入
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    request = urllib2.Request(link, headers=headers)
    image = urllib2.urlopen(request).read()
    filename = '000' + link[-10:]
    with open(filename, "wb") as f:
        f.write(image)
    print '图片已下载' + filename


def tiebaSpider(url, beginPage, endPage):
    """
        作用：贴吧爬虫调度器，负责组合处理每个页面的url
        url : 贴吧url的前部分
        beginPage : 起始页
        endPage : 结束页
    """
    for page in range(beginPage, endPage + 1):
        pn = (page - 1) * 50
        fullurl = url + "&pn=" + str(pn)
        print('贴吧地址：' + fullurl)
        loadPage(fullurl)
        print "谢谢使用"


if __name__ == "__main__":
    kw = raw_input("请输入需要爬取的贴吧名:")
    beginPage = int(raw_input("请输入起始页："))
    endPage = int(raw_input("请输入结束页："))

    url = "http://tieba.baidu.com/f?"
    key = urllib.urlencode({"kw": kw})
    fullurl = url + key
    tiebaSpider(fullurl, beginPage, endPage)
